#!/bin/bash

# Redis-rs2 集群状态检查脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

clear
echo -e "${CYAN}📊 Redis-rs2 集群状态监控${NC}"
echo -e "${CYAN}============================${NC}"
echo

# 定义节点信息
declare -a NODES=("node1" "node2" "node3" "node4" "node5" "node6" "node7")
declare -a PORTS=("7001" "7002" "7003" "7004" "7005" "7006" "7007")
declare -a CLUSTER_PORTS=("17001" "17002" "17003" "17004" "17005" "17006" "17007")
declare -a ROLES=("主节点" "主节点" "主节点" "主节点" "从节点1" "从节点2" "从节点3")

running_count=0
failed_count=0

echo -e "${BLUE}🔍 检查节点运行状态：${NC}"
echo "┌──────────┬────────────┬─────────────┬─────────────┬──────────┐"
echo "│   节点   │    角色    │  Redis端口  │  集群端口   │   状态   │"
echo "├──────────┼────────────┼─────────────┼─────────────┼──────────┤"

for i in "${!NODES[@]}"; do
    node="${NODES[$i]}"
    port="${PORTS[$i]}"
    cluster_port="${CLUSTER_PORTS[$i]}"
    role="${ROLES[$i]}"
    pidfile="logs/cluster/${node}.pid"
    
    # 检查进程状态
    process_status="❌ 停止"
    redis_status="❌ 不可达"
    cluster_status="❌ 不可达"
    
    if [ -f "$pidfile" ]; then
        pid=$(cat "$pidfile")
        if ps -p $pid > /dev/null 2>&1; then
            process_status="✅ 运行"
            
            # 检查Redis端口
            if nc -z 127.0.0.1 $port 2>/dev/null; then
                redis_status="✅ 可达"
            fi
            
            # 检查集群端口
            if nc -z 127.0.0.1 $cluster_port 2>/dev/null; then
                cluster_status="✅ 可达"
            fi
            
            if [ "$redis_status" = "✅ 可达" ] && [ "$cluster_status" = "✅ 可达" ]; then
                running_count=$((running_count + 1))
                status_color="${GREEN}"
            else
                failed_count=$((failed_count + 1))
                status_color="${YELLOW}"
            fi
        else
            failed_count=$((failed_count + 1))
            status_color="${RED}"
        fi
    else
        failed_count=$((failed_count + 1))
        status_color="${RED}"
    fi
    
    # 格式化输出
    printf "│ %-8s │ %-10s │ %-11s │ %-11s │ %s%-8s%s │\n" \
        "$node" "$role" "$port" "$cluster_port" "$status_color" "$process_status" "$NC"
done

echo "└──────────┴────────────┴─────────────┴─────────────┴──────────┘"
echo

# 集群健康状态总结
echo -e "${BLUE}📈 集群健康状态：${NC}"
echo -e "   🟢 运行中节点: ${GREEN}${running_count}/7${NC}"
echo -e "   🔴 故障节点: ${RED}${failed_count}/7${NC}"

if [ $running_count -eq 7 ]; then
    echo -e "   💚 集群状态: ${GREEN}健康${NC}"
elif [ $running_count -ge 4 ]; then
    echo -e "   💛 集群状态: ${YELLOW}部分可用${NC}"
else
    echo -e "   💔 集群状态: ${RED}不可用${NC}"
fi

echo

# 网络连通性测试
echo -e "${BLUE}🌐 网络连通性测试：${NC}"
success_count=0
for i in "${!PORTS[@]}"; do
    port="${PORTS[$i]}"
    node="${NODES[$i]}"
    
    if timeout 2 bash -c "echo > /dev/tcp/127.0.0.1/$port" 2>/dev/null; then
        echo -e "   ✅ ${node} (${port}) 连接成功"
        success_count=$((success_count + 1))
    else
        echo -e "   ❌ ${node} (${port}) 连接失败"
    fi
done

echo -e "   📊 连接成功率: ${success_count}/7 ($(( success_count * 100 / 7 ))%)"
echo

# 资源使用情况
echo -e "${BLUE}💾 资源使用情况：${NC}"
total_memory=0
total_cpu=0
process_count=0

for node in "${NODES[@]}"; do
    pidfile="logs/cluster/${node}.pid"
    if [ -f "$pidfile" ]; then
        pid=$(cat "$pidfile")
        if ps -p $pid > /dev/null 2>&1; then
            # 获取内存和CPU使用率
            if command -v ps &> /dev/null; then
                memory=$(ps -o pid,rss -p $pid 2>/dev/null | tail -n 1 | awk '{print $2}')
                if [ ! -z "$memory" ] && [ "$memory" -gt 0 ]; then
                    total_memory=$((total_memory + memory))
                    process_count=$((process_count + 1))
                    echo -e "   📊 ${node}: $(( memory / 1024 )) MB"
                fi
            fi
        fi
    fi
done

if [ $process_count -gt 0 ]; then
    echo -e "   💾 总内存使用: $(( total_memory / 1024 )) MB"
fi

echo

# 最近的日志错误
echo -e "${BLUE}📋 最近的错误日志：${NC}"
error_found=false

for node in "${NODES[@]}"; do
    logfile="logs/cluster/${node}.log"
    if [ -f "$logfile" ]; then
        recent_errors=$(tail -n 50 "$logfile" | grep -i -E "(error|failed|panic|fatal)" | tail -n 3)
        if [ ! -z "$recent_errors" ]; then
            if [ "$error_found" = false ]; then
                error_found=true
            fi
            echo -e "   🔴 ${node}:"
            echo "$recent_errors" | sed 's/^/      /'
        fi
    fi
done

if [ "$error_found" = false ]; then
    echo -e "   ✅ ${GREEN}没有发现错误日志${NC}"
fi

echo

# 操作提示
echo -e "${CYAN}🔧 可用操作：${NC}"
echo -e "   📝 查看详细日志: ${BLUE}tail -f logs/cluster/<节点名>.log${NC}"
echo -e "   🔄 重启集群: ${BLUE}./scripts/restart_cluster.sh${NC}"
echo -e "   🛑 停止集群: ${BLUE}./scripts/stop_cluster.sh${NC}"
echo -e "   🧪 运行测试: ${BLUE}./scripts/test_cluster.sh${NC}"
echo -e "   📊 持续监控: ${BLUE}watch -n 5 ./scripts/cluster_status.sh${NC}"

echo
echo -e "${CYAN}⏰ 检查时间: $(date)${NC}"